/**
 * Validator
 */

 var validators = require("./validators");
 var validatorMappings = require("./validatorMappings");
 var Validator = function (){
    var _cache = [];
    return {
        // example: addRule(dom, [{validator:"min:6", error:"长度不能小于６位！"}, {validator:"empty", error:"名称不能为空！"}]);
        // optional { extra:{value: "", spliter: ""} }
        addRule: function (dom, rules){
            // 可接受第一个参数为节点或者value值
            var value = dom instanceof jQuery ? dom.val().trim() : dom;
            for (var i = 0, rule; rule = rules[i++];){
                (function (rule){
                    var validatorAry = rule.validator.split(":");
                    var extra, extraValue, extraParam;
                    var error = rule.error;

                    if (rule.extra){
                        extra = rule.extra;
                        extraValue = extra.value;
                        extraParam = extra.spliter;
                    }

                    _cache.push(function (){
                        var validator = validatorAry.shift();

                        validatorAry.unshift(error);

                        extraParam && (validatorAry.unshift(extraParam));
                        extraValue && (validatorAry.unshift(extraValue));

                        validatorAry.unshift(value);

                        if (rule.length) validatorAry.push(rule.length);
                        return validators[validatorMappings[validator]].apply(dom, validatorAry);
                    });
                })(rule);
            }
        },
        execute: function (){
            for (var i = 0, validatorFunc; validatorFunc = _cache[i++];){
                var msg = validatorFunc();
                if (msg){
                    return msg;
                }
            }
        }
    };
 };

 module.exports = Validator;
